import _ from '../../../utils/under-dash';
import defaultNumFormats from '../../defaultnumformats';

import BaseXform from '../base-xform';

function hashDefaultFormats() {
    const hash = {};
    _.each(defaultNumFormats, (dnf, id) => {
        if (dnf.f) {
            hash[dnf.f] = parseInt(id, 10);
        }
        // at some point, add the other cultures here...
    });
    return hash;
}

const defaultFmtHash = hashDefaultFormats();

// NumFmt encapsulates translation between number format and xlsx
class NumFmtXform extends BaseXform {
    constructor(id, formatCode) {
        super();

        this.id = id;
        this.formatCode = formatCode;
    }

    get tag() {
        return 'numFmt';
    }

    render(xmlStream, model) {
        xmlStream.leafNode('numFmt', { numFmtId: model.id, formatCode: model.formatCode });
    }

    parseXmlObject(node) {
        switch (node._name) {
            case 'numFmt':
                this.model = {
                    id: parseInt(node._attributes.numFmtId, 10),
                    formatCode: node._attributes.formatCode.replace(/[\\](.)/g, '$1'),
                };
                return true;
            default:
                return false;
        }
    }

    parseOpen(node) {
        switch (node.name) {
            case 'numFmt':
                this.model = {
                    id: parseInt(node.attributes.numFmtId, 10),
                    formatCode: node.attributes.formatCode.replace(/[\\](.)/g, '$1'),
                };
                return true;
            default:
                return false;
        }
    }

    parseText() {
    }

    parseClose() {
        return false;
    }
}

NumFmtXform.getDefaultFmtId = function getDefaultFmtId(formatCode) {
    return defaultFmtHash[formatCode];
};

NumFmtXform.getDefaultFmtCode = function getDefaultFmtCode(numFmtId) {
    return defaultNumFormats[numFmtId] && defaultNumFormats[numFmtId].f;
};

export default NumFmtXform;
